
package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.ShoppingCartService;
import com.sun.org.apache.bcel.internal.generic.LNEG;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("shoppingCart")
public class ShoppingCartController {

    @Autowired
    private HttpSession session;

    @Autowired
    private ShoppingCartService shoppingCartService;
    @RequestMapping("/list")
    public R<List<ShoppingCart>> findshoppingCartList(){
        User loginUser = (User) session.getAttribute("loginUser");
        return shoppingCartService.findShoppingCartByUserId(loginUser.getId());
    }


    /**
     * 添加购物车
     * @param shoppingCart
     * @return
     */
    @PostMapping("/add")
    public R<ShoppingCart> addShoppingCart(@RequestBody ShoppingCart shoppingCart){
        User loginUser = (User) session.getAttribute("loginUser");
        shoppingCart.setUserId(loginUser.getId());
        return shoppingCartService.addShoppingCart(shoppingCart);
    }

    /**
     * 减少
     * @param shoppingCart
     * @return
     */
    @PostMapping("/sub")
    public R<ShoppingCart> subShoppingCart(@RequestBody ShoppingCart shoppingCart){
        User loginUser = (User) session.getAttribute("loginUser");
        shoppingCart.setUserId(loginUser.getId());
        return shoppingCartService.subShoppingCart(shoppingCart);
    }

    @DeleteMapping("/clean")
    public R<String> cleanShoppingCart(){
        User loginUser = (User) session.getAttribute("loginUser");
        return shoppingCartService.cleanShoppingCart(loginUser.getId())>0?R.success("清空成功"):R.error("清空失败");
    }
}
